$(function() {
	
	//订单取消类型
    sys.selectpicker({
        id : 'cancelReasonCombo', // select的id
        url : rootPath + "/dict/listKeyMapEntites", // 请求数据的远程地址
        param : {
            keyType : 'orderCancelReason'
        }, // 过滤参数
        // defaultValue:{},
        valueField : 'keyValue',
        textField : 'keyIntro'
    });
    
    $("#cancelReasonCombo").on("change", function() {
        $("#cancelReason").val($("#cancelReasonCombo option:selected").text());
    });
	
	sys.daterangepicker({
		id : 'orderTime',
		type : 'date',
		// startDate: moment().subtract(2, "days"), //当前时间减去一天时间
		maxDate : '2099-12-31'
	});
	$("#orderTime").val("");
		
	// 定义列
	var columns = [
		{
				field : 'no',
				title : '序号',
				checkbox : true,
				width:"2%"
		},
		{
				field : 'orderCode',
				title : '订单信息',
				align : 'center',
				formatter : function(value, row, index) {
					var productDetailBuf = "";
					if(row.productList && row.productList.length > 0){
						for(var i = 0; i < row.productList.length; i ++){
							var detail = row.productList[i];
							var price_td = "";
							if(detail.productPrice != detail.productAdjustPrice){
								price_td = "	<span>调价后：¥"+numberRand2(detail.productAdjustPrice)+"</span><br/>"+
		                        "<span style='text-decoration:line-through;'>原价：¥"+detail.productPrice+"</span>";
							}else{
								price_td = "<span>原价：¥"+detail.productPrice+"</span>";
							}
							
							var spec_str = "";
							if(detail.productSpecList && detail.productSpecList.length > 0){
								spec_str = "【"
								for(var j = 0 ;j < detail.productSpecList.length; j++){
									var spec = detail.productSpecList[j];
									spec_str += spec.specName+":"+ spec.specValue + " ";
								}
							}
							if(spec_str != ""){
								spec_str += "】";
							}
							
							productDetailBuf+="" +
								"<tr>" +
								"	<td style='width:50px;text-align:center;'>" +
								"		<a rel='productImg' href='"+imgRootURL+detail.imagePath+"'>" +
								"			<img style='float:left;width:48px;height:48px;border:1px solid #e8e8e8;' src='"+imgRootURL+detail.imagePath+"?x-oss-process=image/resize,h_60/format,png' />" +
								"		</a>" +
								"	</td>" +
								"	<td style='width:300px;border-left:0px solid #fff;'>"+detail.productName+"<br/>"+spec_str+"</td>" +
								"	<td style='width:150px;border-left:0px solid #fff;text-align:right;'>"+
									price_td+
								"   </td>" +
								"	<td style='width:100px;border-left:0px solid #fff;'>购买数量："+detail.buyNum+"</td>" +
								"</tr>";
						}
					}
					
					var deliveryHtml = "";
					if(row.deliveryInfo) {
						deliveryHtml = "<span>物流：" + row.deliveryInfo + "</span>";
					}
					
					return "<div class='order_row'>" +
							"<div class='order_row_info'>" +
								"<div><span class='order_status'>"+row.orderStatusName+"</span></div>" +
								"<div class='order_field'><span>订单号："+row.orderCode+"</span><span>下单时间："+row.orderTimeStr+"</span><span>客户名称："+row.customerName+"</span><span>客户电话："+row.customerMobile+"</span><span>客户单位："+row.customerCompanyName+"</span>" + deliveryHtml + "</div>" +
							"</div>" +
							"<div class='order_separator'></div>"+
							"<div>" +
							"<table class='order_detail_product_table'>" +
								productDetailBuf+
							"</table>" +
							"</div>"
			                "</div>";
				}
		},
		{	
			field : '#',
			title : '支付信息',
			align : 'center',
			formatter : function(value, row, index) {
				var payTypeNameHtm = row.payTypeName;
				// 如果已支付，显示支付方式
				if(payTypeNameHtm) {
					if(row.payType == '04' && row.bankName) {
						// 私人银行打款,把银行名称带着
						payTypeNameHtm = payTypeNameHtm + "(" + row.bankName + ")";
					}
				} else {
					// 尚未支付，显示支付模式（在线支付、货到付款）
					payTypeNameHtm = row.payModelName;
				}
				var text = "<div class='order_pay_info'>" +
					"<div>" +
						"<div style='display:inline-block;'><span>应付</span><span class='order_money' style='color:#FC5457;'>￥"+row.realPayMoney+"</span></div>" +
							"<div><span>总计</span><span>￥"+row.orderMoney+"</span></div>" +
						"</div>" +
						"<div class='order_separator'></div>"+
						"<div><span>" + payTypeNameHtm +"<span></div>";
//				if(row.payModel == '01' && row.orderStatus == '01'){
//					text += "<div><button type='button' class='btn btn-primary btn-xs'>调价</button></div>";
//				}
				text += "</div>";
				return text;
			},
			width: "15%"
		},
		{	
			field : '#',
			title : '操作',
			align : 'center',
			formatter : function(value, row, index) {
				var resultStr = "";
				resultStr += "<div class='order_pay_operation'>";
				// 立即支付+待付款      或者 货到付款+待上传合同 
				if((row.payModel == '01' && row.orderStatus == '01') || (row.payModel == '02' && row.orderStatus == '09')){
					resultStr +=	"<div><button class='btn btn-danger btn-sm' type='button'  onclick='toAdjustOrderProductPrice(\""+row.orderCode+"\")'>调价</button></div>";
				}
				if(row.orderStatus == '01' && !(row.payModel == '02' && row.orderStatus == '01')){
					resultStr +=	"<div><button class='btn btn-default btn-sm' style='margin-top:2px;' type='button' onclick='openCancelWin(\""+row.orderCode+"\")'>取消</button></div>";
				}
				resultStr +=	"<div><button class='btn btn-default btn-sm' style='margin-top:2px;' type='button' onclick='toOrderDetail(\""+row.orderCode+"\")'>详情</button></div>";
				resultStr += "</div>";
				return resultStr;
			},
			width: "15%"
		} ];
			
	// 查询时间类型
	var time_type = '';
	
	// 定义查询回调函数（查询参数在此设置）
	var queryParams = function(params) {
	
		var searchKey =  $("#searchKey").val()
		var orderStatus = $("#orderStatus").val();
		var payModel = $("#payModel").val();
		var adjustPriceFlag = $("#adjustPriceFlag").val();
		
		var orderCode = $("#orderCode").val();
		var customerName = $("#customerName").val();
		var customerMobile = $("#customerMobile").val();
		var customerCompanyName = $("#customerCompanyName").val();
		var salesmanName = $("#salesmanName").val();
		var orderTime = $("#orderTime").val();
		// 如果有时间类型将时间条件取消
		if(!time_type && time_type != null){
			orderTime = "";
		}
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码
			searchKey : searchKey,
			orderStatus : orderStatus,
			payModel: payModel,
			adjustPriceFlag: adjustPriceFlag,
			orderCode : orderCode,
			customerName : customerName,
			customerMobile : customerMobile,
			customerCompanyName : customerCompanyName,
			salesmanName : salesmanName,
			orderTime : orderTime,
			timeType : time_type
		};
	};
	
	var url = rootPath + "/order/listOrderPage"; // 请求json数据的服务器地址
	sys.initTable('orderTable', {
		url : url,
		queryParams : queryParams,
		columns : columns,
		striped : true,
		clickToSelect : true,
		onLoadSuccess : function(){
			initBootstrapTableCheckbox();
            initFancyBoxImg("productImg");
		}
	});

	// 查询方式1
	$('#btn_query_all_order').on('click', function() {
		$("#orderCode").val("");
		$("#customerName").val("");
		$("#customerMobile").val("");
		$("#customerCompanyName").val("");
		$("#salesmanName").val("");
		$("#orderTime").val("");
		sys.reloadTable('orderTable');
	});
	//查询方式2
	$("#btnQuery").on('click', function(){
		$("#searchKey").val("");
		sys.reloadTable('orderTable');
	});

	// 清空
	$('#btnClear').on('click', function() {
		$("#orderCode").val("");
		$("#customerName").val("");
		$("#customerMobile").val("");
		$("#customerCompanyName").val("");
		$("#salesmanName").val("");
		$("#orderTime").val("");
		$("#searchKey").val("");
	});
	
	//切换搜索条件
	$("#btnChange1").on('click', function(){
		$("#searchKey").val("");
		$("#search_bar_1").hide();
		$("#search_bar_2").show();
		$("#btn_query_all_order").removeClass("search");
		$("#btnQuery").addClass("search");
	});
	$("#btnChange2").on('click', function(){
		$("#orderCode").val("");
		$("#customerName").val("");
		$("#customerMobile").val("");
		$("#customerCompanyName").val("");
		$("#salesmanName").val("");
		$("#orderTime").val("");
		$("#search_bar_2").hide();
		$("#search_bar_1").show();
		$("#btnQuery").removeClass("search");
		$("#btn_query_all_order").addClass("search");
	});
	
	//分类查询
	$("#model_type").find("a").each(function(){
		$(this).on("click",function(){
			$("#model_type").find("a").attr("class","order_search_tag");
			$(this).attr("class","order_search_tag_current");
			var key = $(this).attr("name");
			if (key == "pay_now") {
				$("#payModel").val("01");
			} else if(key == "pay_delivery"){
				$("#payModel").val("02");
			} else {
				$("#payModel").val("");
			}
			if (key == "adjust_price") {
				$("#adjustPriceFlag").val("2");
			} else {
				$("#adjustPriceFlag").val("");
			}
			if(key=="all"){
				$("#payModel").val("");
				$("#adjustPriceFlag").val("");
			}
			sys.reloadTable('orderTable');
		});
	});

	// 最近订单查询s
	$("#btn_group_search").find("button[id^='btn_']").each(function(i,item){
		$(this).click(function(){
			//清除其他搜索方式的日期搜索
			$("#orderTime").val("");
			var class_type = $(this).hasClass("btn-info");
			var timeType  = $(this).attr("id").substring(4);
			$("#btn_group_search").find("button[id^='btn_']").each(function(i,item){
				$(this).removeClass("btn-warning");
				$(this).addClass("btn-info");
			});
			if(class_type){
				$(this).removeClass("btn-info");
				$(this).addClass("btn-warning");
				time_type = timeType;
			}else{
				$(this).removeClass("btn-warning");
				$(this).addClass("btn-info");
				time_type = "";
			}
			$(this).blur();
			// $("#orderTable").bootstrapTable("refresh",{query: {timeType: timeType}});
			sys.reloadTable('orderTable');
		});
	});
	
	// 导出订单
	$("#btn_export_order").click(function(){
		var searchKey =  $("#searchKey").val();
		var orderStatus = $("#orderStatus").val();
		var payModel = $("#payModel").val();
		var adjustPriceFlag = $("#adjustPriceFlag").val();
		
		var orderCode = $("#orderCode").val();
		var customerName = $("#customerName").val();
		var customerMobile = $("#customerMobile").val();
		var customerCompanyName = $("#customerCompanyName").val();
		var salesmanName = $("#salesmanName").val();
		var orderTime = $("#orderTime").val();
		
		var btn_selected = $("#btn_group_search").find("button.btn-warning");
		var timeType = "";
		if(!btn_selected && btn_selected.attr("id") != undefined){
			timeType = $("#btn_group_search").find("button.btn-warning").attr("id").substring(4);
		}
		var form = getForm("/order/exportOrder");
		form.append("<input type='hidden'  name='searchKey'  value='"+searchKey+"'/>");
		form.append("<input type='hidden'  name='orderStatus'  value='"+orderStatus+"'/>");
		form.append("<input type='hidden'  name='payModel'  value='"+payModel+"'/>");
		form.append("<input type='hidden'  name='adjustPriceFlag'  value='"+adjustPriceFlag+"'/>");
		form.append("<input type='hidden'  name='orderCode'  value='"+orderCode+"'/>");
		form.append("<input type='hidden'  name='customerName'  value='"+customerName+"'/>");
		form.append("<input type='hidden'  name='customerMobile'  value='"+customerMobile+"'/>");
		form.append("<input type='hidden'  name='customerCompanyName'  value='"+customerCompanyName+"'/>");
		form.append("<input type='hidden'  name='salesmanName'  value='"+salesmanName+"'/>");
		form.append("<input type='hidden'  name='orderTime'  value='"+orderTime+"'/>");
		form.append("<input type='hidden'  name='timeType'  value='"+timeType+"'/>");
		form.submit();
	});
	
	// 打印订单
	$("#btn_print_order").click(function(){
		var checkedSize = $("div.checked").length;
		if(checkedSize == 0){
			layer.alert('请选择要打印的订单');
			return false;
		}
		if(checkedSize > 1){
			layer.alert('每次只能打印一条订单');
			return false;
		}
		var index = $("div.checked").closest("tr").attr("data-index");
		var row = $("#orderTable").bootstrapTable("getData")[index];
		window.location.href = rootPath + "/order/toPrintOrder?orderCode=" +row.orderCode+"&fromPage=02";
	});
	
})

// 跳转订单详情页面
function toOrderDetail(orderCode){
	window.location.href = rootPath + "/order/toOrderDetail?orderCode="+orderCode+"&tabIndex=1";
}

// 弹窗订单调价页面
function toAdjustOrderProductPrice(orderCode){
	var url = rootPath + "/order/toAdjustOrderProductPrice?orderCode="+orderCode;
	var winIndex = layer.open({
		  type: 2,//弹框类型
		  title: '添加商品模板属性',//弹框标题
		  area: ['900px', '600px'],//弹框大小，宽高
		  skin: 'layui-layer-lan',//皮肤
		  fixed: false, //是否固定，不固定
		  content: url,//加载内容，可以是一句话也可以是连接
		  shade:[0.8, '#393D49'],//遮罩，透明度以及颜色
		  cancel: function(index, layero){ 
			  layer.close(index)
			  return false; 
		  }
	});
	//最大化
	layer.full(winIndex);
}

/**
 * 打开弹出层
 * @Description do-something
 * @author xu_cc
 * @date 创建时间：2018年2月24日 下午3:03:31
 * @param orderCode
 */
function openCancelWin(orderCode) {
	$("#cancelOrderCode").val(orderCode);
	$("#cancelReason").val($("#cancelReasonCombo option:selected").text());
	$("#cancelModal").modal('show');
}

//取消订单
function doCancelOrder(){
	var url = rootPath + "/order/cancelOrder";
	var orderCode = $("#cancelOrderCode").val();
	if(orderCode) {
		var params = {
				orderCode : orderCode
		};
		
		$.ajax({
			type:"post",
			url:url,
			data:params,
			datatype: "json",
			success:function(json){
				$("#cancelModal").modal('hide');
				if(json.resultCode == '1') {
					layer.alert('取消成功', { icon: 6});
					$("#orderTable").bootstrapTable("refresh");
				} else {
					showMsg(json.resultMsg);
				}
			},
			error: function(){
				sys.showErr("取消失败");
			}
		});
		/*
		layer.confirm('您确定要取消该订单吗？',{
			btn: ['确定','取消'], //按钮
			skin: 'layui-layer-lan' //样式类名
			}, function(index, layero){
				
			}, 
			function(index){
				$("#cancelModal").modal('hide');
			}
		);
		*/
	} else {
		sys.showErr("取消失败！");
	}
}
